package controllers

import (
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"oceanLearn/common"
	"oceanLearn/models"
	"oceanLearn/response"
	"strconv"
)

type ICategoryController interface {
	RestController
}

type CategoryController struct {
	DB *gorm.DB
}

func NewCategoryController() ICategoryController {
	db := common.GetDB()
	db.AutoMigrate(models.Category{})
	return CategoryController{DB: db}
}

// 让结构体实现这个接口
func (c CategoryController) Create(ctx *gin.Context) {
	var requestCategory models.Category
	ctx.Bind(&requestCategory)

	if requestCategory.Name == "" {
		response.Fail(ctx, "数据验证错误，分类名称必填", nil)
		return
	}
	c.DB.Create(&requestCategory)
	response.Success(ctx,"createSuccess",gin.H{"Category": requestCategory.Name})
}

func (c CategoryController) Update(ctx *gin.Context) {
	// 绑定body中的参数
	var requestCategory models.Category
	ctx.Bind(&requestCategory)

	if requestCategory.Name == "" {
		response.Fail(ctx, "数据验证错误，分类名称必填", nil)
		return
	}

	// 获取path中的参数
	categoryId, _ :=strconv.Atoi(ctx.Params.ByName("id"))
	var updateCategory models.Category
	if c.DB.First(&updateCategory,categoryId).RecordNotFound(){
		response.Fail(ctx, "分类不存在", nil)
		return
	}

	c.DB.Model(&updateCategory).Update("name", requestCategory.Name)
	response.Success(ctx, "修改成功", gin.H{"category":updateCategory})
	//更新分类
	//map
	//struct
	//name value
}

func (c CategoryController) Show(ctx *gin.Context) {
	// 获取path中的参数
	categoryId, _ :=strconv.Atoi(ctx.Params.ByName("id"))
	var category models.Category
	if c.DB.First(&category,categoryId).RecordNotFound(){
		response.Fail(ctx, "分类不存在", nil)
		return
	}
	response.Success(ctx, "查询成功", gin.H{"category":category})
}

func (c CategoryController) Delete(ctx *gin.Context) {
	categoryId, _ :=strconv.Atoi(ctx.Params.ByName("id"))

	if err := c.DB.Delete(models.Category{},categoryId).Error;err !=nil{
		response.Fail(ctx, "删除失败，请重试", nil)
		return
	}
	response.Success(ctx, "删除成功", nil)
}
